package com.example.aevovein.ui.skilltree;

import android.app.AlertDialog;
import android.app.Dialog;
import android.os.Bundle;
import android.os.Environment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.example.aevovein.R;
import com.example.aevovein.databinding.FragmentSkilltreeBinding;
import com.example.aevovein.model.Skill;
import com.google.gson.Gson;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class SkilltreeFragment extends Fragment {
    private FragmentSkilltreeBinding binding;
    private SkilltreeAdapter adapter;
    private final Gson gson = new Gson();
    private SkilltreeViewModel skilltreeViewModel;
    private Spinner spinnerSkillTree;
    private ArrayAdapter<String> spinnerAdapter;

    // 保存当前选择的技能类型
    private String currentSkillType = "练字";
    private RadarChartView radarChartView; // 引入自定义雷达图控件

    public View onCreateView(@NonNull LayoutInflater inflater,
                             ViewGroup container, Bundle savedInstanceState) {
        skilltreeViewModel = new ViewModelProvider(this).get(SkilltreeViewModel.class);
        binding = FragmentSkilltreeBinding.inflate(inflater, container, false);
        View root = binding.getRoot();

        // 获取自定义雷达图控件
        radarChartView = binding.radarChartView;

        // 设置RecyclerView
        RecyclerView recyclerView = binding.recyclerSkilltree;
        recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));

        // 设置添加技能按钮
        binding.btnAddSkill.setOnClickListener(v -> showAddSkillDialog());

        // 设置技能树选择器
        spinnerSkillTree = binding.spinnerSkillTree;
        spinnerAdapter = new ArrayAdapter<>(requireContext(), 
            android.R.layout.simple_spinner_item, new ArrayList<>());
        spinnerAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinnerSkillTree.setAdapter(spinnerAdapter);

        // 设置添加技能树按钮
        binding.btnAddSkillTree.setOnClickListener(v -> showAddSkillTreeDialog());

        // 设置删除技能树按钮
        binding.btnDeleteSkillTree.setOnClickListener(v -> showDeleteSkillTreeDialog());

        // 监听技能树选择变化
        spinnerSkillTree.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                String selectedType = (String) parent.getItemAtPosition(position);
                if (!selectedType.equals(currentSkillType)) {
                    currentSkillType = selectedType;
                    loadSkills();
                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {}
        });

        loadSkills();

        return root;
    }

    private void loadSkills() {
        skilltreeViewModel.getSkillsMap().observe(getViewLifecycleOwner(), skillMap -> {
            if (skillMap != null) {
                // 更新下拉选择框
                List<String> skillTypes = new ArrayList<>(skillMap.keySet());
                spinnerAdapter.clear();
                spinnerAdapter.addAll(skillTypes);
                
                // 设置当前选中的技能类型
                int position = skillTypes.indexOf(currentSkillType);
                if (position >= 0) {
                    spinnerSkillTree.setSelection(position);
                }

                // 加载当前技能类型的技能
                if (skillMap.containsKey(currentSkillType)) {
                    List<Skill> skills = skillMap.get(currentSkillType);
                    if (adapter == null) {
                        adapter = new SkilltreeAdapter(getContext(), skills, new SkilltreeAdapter.SkillUpdateListener() {
                            @Override
                            public void onSkillUpdated(Skill skill, int delta) {
                                updateSkill(skill, delta);
                            }

                            @Override
                            public void onSkillDeleted(Skill skill) {
                                deleteSkill(skill);
                            }
                        });
                        binding.recyclerSkilltree.setAdapter(adapter);
                    } else {
                        adapter.updateSkills(skills);
                    }

                    // 更新雷达图数据
                    updateRadarChart(skills);
                }
            }
        });
    }

    private void updateSkill(Skill skill, int delta) {
        skill.setLevel(Math.max(0, Math.min(100, skill.getLevel() + delta)));
        adapter.notifyDataSetChanged();
        saveSkills();
        updateRadarChart(skilltreeViewModel.getSkillsMap().getValue().get(currentSkillType)); // 更新雷达图
    }

    private void deleteSkill(Skill skill) {
        // 显示确认对话框
        new AlertDialog.Builder(requireContext())
            .setTitle("删除技能")
            .setMessage("确定要删除技能 \"" + skill.getName() + "\" 吗？")
            .setPositiveButton("确定", (dialog, which) -> {
                // 从技能列表中移除
                List<Skill> skills = skilltreeViewModel.getSkillsMap().getValue().get(currentSkillType);
                skills.removeIf(s -> s.getId().equals(skill.getId()));
                
                // 更新适配器
                adapter.updateSkills(skills);
                
                // 更新雷达图
                updateRadarChart(skills);
                
                // 保存到文件
                saveSkills();
                
                Toast.makeText(requireContext(), "技能已删除", Toast.LENGTH_SHORT).show();
            })
            .setNegativeButton("取消", null)
            .show();
    }

    private void updateRadarChart(List<Skill> skills) {
        if (skills != null && radarChartView != null) {
            List<Integer> entries = new ArrayList<>();
            List<String> labels = new ArrayList<>();
            for (Skill skill : skills) {
                entries.add(skill.getLevel());
                labels.add(skill.getName());
            }
            radarChartView.setValues(entries, labels, 100); // 传递标签列表
        }
    }

    private void saveSkills() {
        File dataDir = new File(Environment.getExternalStorageDirectory(), "AevoVein/data");
        File skilltreeFile = new File(dataDir, "skilltree.json");
        try (FileWriter writer = new FileWriter(skilltreeFile)) {
            Map<String, List<Skill>> skillMap = skilltreeViewModel.getSkillsMap().getValue();
            if (skillMap != null) {
                gson.toJson(skillMap, writer);
            }
        } catch (IOException e) {
            e.printStackTrace();
            if (getContext() != null) {
                Toast.makeText(getContext(), "保存技能数据失败: " + e.getMessage(), Toast.LENGTH_SHORT).show();
            }
        }
    }

    private void showAddSkillDialog() {
        Dialog dialog = new Dialog(requireContext());
        dialog.setContentView(R.layout.dialog_add_skill);
        dialog.getWindow().setLayout(ViewGroup.LayoutParams.MATCH_PARENT, 
                                    ViewGroup.LayoutParams.WRAP_CONTENT);

        EditText editTextSkillName = dialog.findViewById(R.id.editTextSkillName);
        EditText editTextSkillId = dialog.findViewById(R.id.editTextSkillId);
        EditText editTextSkillDescription = dialog.findViewById(R.id.editTextSkillDescription);
        Button buttonConfirm = dialog.findViewById(R.id.buttonConfirm);
        Button buttonCancel = dialog.findViewById(R.id.buttonCancel);

        buttonConfirm.setOnClickListener(v -> {
            String name = editTextSkillName.getText().toString().trim();
            String idSuffix = editTextSkillId.getText().toString().trim();
            String description = editTextSkillDescription.getText().toString().trim();

            // 验证输入
            if (name.isEmpty() || idSuffix.isEmpty() || description.isEmpty()) {
                Toast.makeText(requireContext(), "请填写所有字段", Toast.LENGTH_SHORT).show();
                return;
            }

            // 验证ID后缀格式（只允许英文字母和下划线）
            if (!idSuffix.matches("^[a-zA-Z_]+$")) {
                Toast.makeText(requireContext(), "技能ID只能包含英文字母和下划线", Toast.LENGTH_SHORT).show();
                return;
            }

            // 创建新技能
            Skill newSkill = new Skill();
            newSkill.setId("skill." + idSuffix);
            newSkill.setName(name);
            newSkill.setDescription(description);
            newSkill.setLevel(0);
            newSkill.setMaxLevel(100);

            // 添加到当前技能类型中
            List<Skill> skills = skilltreeViewModel.getSkillsMap().getValue().get(currentSkillType);
            skills.add(newSkill);

            // 更新适配器
            adapter.updateSkills(skills);

            // 更新雷达图
            updateRadarChart(skills);

            // 保存到文件
            saveSkills();

            Toast.makeText(requireContext(), "技能添加成功", Toast.LENGTH_SHORT).show();
            dialog.dismiss();
        });

        buttonCancel.setOnClickListener(v -> dialog.dismiss());

        dialog.show();
    }

    private void showAddSkillTreeDialog() {
        Dialog dialog = new Dialog(requireContext());
        dialog.setContentView(R.layout.dialog_add_skill_tree);
        dialog.getWindow().setLayout(ViewGroup.LayoutParams.MATCH_PARENT, 
                                    ViewGroup.LayoutParams.WRAP_CONTENT);

        EditText editTextSkillTreeName = dialog.findViewById(R.id.editTextSkillTreeName);
        Button buttonConfirm = dialog.findViewById(R.id.buttonConfirm);
        Button buttonCancel = dialog.findViewById(R.id.buttonCancel);

        buttonConfirm.setOnClickListener(v -> {
            String name = editTextSkillTreeName.getText().toString().trim();
            
            // 验证输入
            if (name.isEmpty()) {
                Toast.makeText(requireContext(), "请输入技能树名称", Toast.LENGTH_SHORT).show();
                return;
            }

            // 检查是否已存在同名技能树
            Map<String, List<Skill>> skillMap = skilltreeViewModel.getSkillsMap().getValue();
            if (skillMap != null && skillMap.containsKey(name)) {
                Toast.makeText(requireContext(), "该技能树已存在", Toast.LENGTH_SHORT).show();
                return;
            }

            // 创建默认技能列表
            List<Skill> defaultSkills = new ArrayList<>();
            
            // 添加默认技能1
            Skill skill1 = new Skill();
            skill1.setId("skill.one");
            skill1.setName("技能1");
            skill1.setDescription("技能描述1");
            skill1.setLevel(0);
            skill1.setMaxLevel(100);
            defaultSkills.add(skill1);

            // 添加默认技能2
            Skill skill2 = new Skill();
            skill2.setId("skill.two");
            skill2.setName("技能2");
            skill2.setDescription("技能描述2");
            skill2.setLevel(0);
            skill2.setMaxLevel(100);
            defaultSkills.add(skill2);

            // 添加默认技能3
            Skill skill3 = new Skill();
            skill3.setId("skill.three");
            skill3.setName("技能3");
            skill3.setDescription("技能描述3");
            skill3.setLevel(0);
            skill3.setMaxLevel(100);
            defaultSkills.add(skill3);

            // 添加到技能树列表中
            skillMap.put(name, defaultSkills);

            // 保存到文件
            saveSkills();

            // 更新UI
            loadSkills();

            Toast.makeText(requireContext(), "技能树创建成功", Toast.LENGTH_SHORT).show();
            dialog.dismiss();
        });

        buttonCancel.setOnClickListener(v -> dialog.dismiss());

        dialog.show();
    }

    private void showDeleteSkillTreeDialog() {
        Map<String, List<Skill>> skillMap = skilltreeViewModel.getSkillsMap().getValue();
        if (skillMap == null || skillMap.size() <= 1) {
            Toast.makeText(requireContext(), "至少保留一个技能树", Toast.LENGTH_SHORT).show();
            return;
        }

        // 创建不包含当前技能类型的列表
        List<String> availableTypes = new ArrayList<>(skillMap.keySet());
        availableTypes.remove(currentSkillType);

        // 创建选择对话框
        new AlertDialog.Builder(requireContext())
            .setTitle("选择要删除的技能树")
            .setItems(availableTypes.toArray(new String[0]), (dialog, which) -> {
                String typeToDelete = availableTypes.get(which);
                // 确认删除
                new AlertDialog.Builder(requireContext())
                    .setTitle("确认删除")
                    .setMessage("确定要删除技能树 \"" + typeToDelete + "\" 吗？")
                    .setPositiveButton("确定", (dialog2, which2) -> {
                        // 从技能树列表中移除
                        skillMap.remove(typeToDelete);
                        
                        // 保存到文件
                        saveSkills();
                        
                        // 更新UI
                        loadSkills();
                        
                        Toast.makeText(requireContext(), "技能树已删除", Toast.LENGTH_SHORT).show();
                    })
                    .setNegativeButton("取消", null)
                    .show();
            })
            .show();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        binding = null;
    }
}